package com.medication.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.jfinal.core.Controller;
import com.medication.model.SecAdminUser;
import com.medication.utils.Md5Utils;

/**
 * 管理员、代理 controller
 */
public class AdminUserController extends Controller {

	public void index() {
		// TODO 获取管理员列表
		List<SecAdminUser> list = SecAdminUser.dao.find("select * from sec_admin_user order by user_name");
		setAttr("userList", list);
		render("admin-list.html");
	}

	public void query() {
		StringBuilder sql = new StringBuilder("select * from sec_admin_user where 1 =1 ");
		String userName = getPara("userName");
		String realName = getPara("realName");
		List<String> params = new ArrayList<String>();
		if (!StringUtils.isEmpty(realName)) {
			sql.append(" and real_name like ?");
			realName = "%" + realName + "%";
			params.add(realName);
		}
		if (!StringUtils.isEmpty(userName)) {
			sql.append(" and user_name like ?");
			userName = "%" + userName + "%";
			params.add(userName);
		}
		setAttr("userList", SecAdminUser.dao.find(sql.toString(), params.toArray()));
		render("admin-list.html");
	}

	/**
	 * add update view
	 */
	public void edit() {
		String userId = getPara("id");
		String role = getPara("role");
		if (StringUtils.isEmpty(userId) && StringUtils.isEmpty(role)
				&& !("agent".equals(role) || "manager".equals(role))) {
			renderError(403);
			return;
		}
		SecAdminUser user = null;
		if (StringUtils.isNotEmpty(userId)) {
			user = SecAdminUser.dao.findById(userId);
			if (user == null) {
				renderError(403);
				return;
			}
		} else {
			user = new SecAdminUser();
			user.setRole(role);
		}
		setAttr("user", user);
		render("admin-edit.html");
	}

	public void save() {
		SecAdminUser adminUser = getBean(SecAdminUser.class, "");
		if (StringUtils.isEmpty(adminUser.getId())) {
			adminUser.setPassword(Md5Utils.Md5("123456"));
			adminUser.save();
		} else {
			adminUser.update();
		}
		redirect("/admin/user/index");
	}

	public void delete() {
		String id = getPara("id");
		SecAdminUser.dao.deleteById(id);
		redirect("/admin/user/index");
	}

	public void updatePassword() {
		String id = getPara("id");
		SecAdminUser user = SecAdminUser.dao.findById(id);
		setAttr("user", user);
		render("admin-update-password.html");

	}

	public void updatePasswordSave() {
		String id = getPara("id");
		String oriPassword = getPara("oriPassword");
		String password = getPara("password");

		SecAdminUser user = SecAdminUser.dao.findById(id);
		if (user != null && user.getPassword().equals(Md5Utils.Md5(oriPassword))) {
			user.setPassword(Md5Utils.Md5(password));
			user.update();
			setAttr("msg", "修改成功");
		} else if (user == null) {
			setAttr("msg", "用户不存在");
		} else {
			setAttr("msg", "旧密码不正确");
		}

		updatePassword();
	}
}
